//
//  ASPersonViewController.m
//  AttendenceSys
//
//  Created by ld on 16/1/14.
//  Copyright © 2016年 窦芳俊. All rights reserved.
//

#import "ASPersonViewController.h"
#import "ASPersonCell.h"
#import "ASLoginUserInfo.h"
#import "ASBasicInfoVC.h"
#import "ASTeacherBasicInfoViewController.h"
#import "ASMyCollectionVC.h"
#import "ASMyMessageVC.h"
#import "ASSettingViewController.h"
#import "ASNetworkEngine.h"
#import "FTPhotoAlbumController.h"
#import "FTAlbumPhotoControllerDelegate.h"
#import "FileUtil.h"
#import "ASPoliticalInfo.h"
#import "ASScanQRCodeVC.h"

@interface ASPersonViewController () <FTAlbumPhotoViewControllerDelegate, ASScanQRCodeViewControllerDelegate>

@property(nonatomic, strong) ASLoginUserInfo* userInfo;

@end


@implementation ASPersonViewController

- (void)initView
{
    //_infoTypeArr = @[@"基本信息", @"我的收藏", @"我的消息", @"设置"];
    //_leftBgImage = @[@"ic_information", @"ic_collection", @"ic_news", @"ic_set"];
    
    if (0 == AS_APP_UserType)
    {
        _infoTypeArr = @[@"基本信息", @"设置", @"扫一扫"];
        _leftBgImage = @[@"ic_information", @"ic_set", @"ic_set"];
    }
    else
    {
        _infoTypeArr = @[@"基本信息", @"设置"];
        _leftBgImage = @[@"ic_information", @"ic_set"];
    }
    
    UIImageView* bgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
    bgView.backgroundColor = [UIColor whiteColor];
    bgView.image = [UIImage imageNamed:@"bg_personal"];
    bgView.userInteractionEnabled = YES;
    [self.view addSubview:bgView];
    
    // userName
    _userName = [[UILabel alloc] initWithFrame:CGRectMake(0, 14, self.view.frame.size.width, 20)];
    [_userName setBackgroundColor:[UIColor clearColor]];
    [_userName setText:_userInfo.userName];
    [_userName setTextColor:[UIColor blackColor]];
    [_userName setTextAlignment:NSTextAlignmentCenter];
    _userName.font = [UIFont fontWithName:@"Arial" size:16.0];
    [bgView addSubview:_userName];
    
    // headImage
    _headImage = [[UIImageView alloc] initWithFrame:CGRectMake((self.view.frame.size.width - 90) / 2,
                                                               _userName.frame.origin.y + _userName.frame.size.height + 8,
                                                               90,
                                                               90)];
    _headImage.backgroundColor = [UIColor clearColor];
    _headImage.layer.cornerRadius = 12.0f;
    _headImage.layer.masksToBounds = YES;
    _headImage.image = [UIImage imageNamed:@"person_portrait_default"];
    [bgView addSubview:_headImage];
    
    // headImage Button
    UIButton *headImageBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    headImageBtn.frame = CGRectMake((self.view.frame.size.width - 90) / 2,
                                    _userName.frame.origin.y + _userName.frame.size.height + 8,
                                    90,
                                    90);
    headImageBtn.backgroundColor = [UIColor clearColor];
    [headImageBtn addTarget:self action:@selector(clickHeadImageBtn:) forControlEvents:UIControlEventTouchUpInside];
    [bgView addSubview:headImageBtn];
    
    // collegeName
    _collegeName = [[UILabel alloc] initWithFrame:CGRectMake(0,
                                                             _headImage.frame.origin.y + _headImage.frame.size.height + 8,
                                                             self.view.frame.size.width,
                                                             20)];
    [_collegeName setBackgroundColor:[UIColor clearColor]];
    [_collegeName setText:_userInfo.majorName];
    [_collegeName setTextColor:[UIColor blackColor]];
    [_collegeName setTextAlignment:NSTextAlignmentCenter];
    _collegeName.font = [UIFont fontWithName:@"Arial" size:15.0];
    [bgView addSubview:_collegeName];
    
    // className
    _className = [[UILabel alloc] initWithFrame:CGRectMake(0,
                                                           _collegeName.frame.origin.y + _collegeName.frame.size.height + 4,
                                                           self.view.frame.size.width,
                                                           20)];
    [_className setBackgroundColor:[UIColor clearColor]];
    //[_className setText:_userInfo.className];
    [_className setText:@""];
    [_className setTextColor:[UIColor blackColor]];
    [_className setTextAlignment:NSTextAlignmentCenter];
    _className.font = [UIFont fontWithName:@"Arial" size:14.0];
    [bgView addSubview:_className];
    
    // infoTableView
    _infoTableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    _infoTableView.frame = CGRectMake(0,
                                      _className.frame.origin.y + _className.frame.size.height + 14,
                                      self.view.frame.size.width,
                                      (0 == AS_APP_UserType) ? 149 : 99);
    _infoTableView.delegate = self;
    _infoTableView.dataSource = self;
    _infoTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _infoTableView.backgroundColor = [UIColor whiteColor];
    [_infoTableView registerClass:[ASPersonCell class] forCellReuseIdentifier:NSStringFromClass([ASPersonCell class])];
    [bgView addSubview:_infoTableView];
    
    // 退出登录
    _logoutBtn = [[UIButton alloc] initWithFrame:CGRectMake(55,
                                                            _infoTableView.frame.origin.y + _infoTableView.frame.size.height + 20,
                                                            self.view.frame.size.width - 2 * 55,
                                                            50)];
    [_logoutBtn setTitle:@"退出登录" forState:UIControlStateNormal];
    [_logoutBtn addTarget:self action:@selector(logout) forControlEvents:UIControlEventTouchUpInside];
    [_logoutBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    _logoutBtn.backgroundColor = RGB(253, 119, 62);
    [bgView addSubview:_logoutBtn];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    if (_politicalArray == nil)
    {
        _politicalArray = [[NSMutableArray alloc] init];
    }
    
    _userInfo = [ASAppDelegate sharedAppDelegate].userInfo;
    [self initView];
    
    // 判断头像是否存在，存在则加载
    NSString *headImageName = @"123.png";
    if ([self judgeFileExist:headImageName])
    {
        NSString *imagePath = [self getHeadImageFilePath:headImageName];
        UIImage *image = [UIImage imageWithContentsOfFile:imagePath];
        if (image)
        {
            _headImage.image = image;
        }
    }
    
    [self fetchUserPolitical];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

- (void)fetchUserPolitical
{
    // http://211.65.216.54/getPoliticalType.action
    NSString *refer = @"getPoliticalType.action";
    NSString *prefix = kASHttpUrl(refer);
    
    typeof(self) __weak weakSelf = self;
    [SVProgressHUD showWithStatus:@"获取中..." maskType:SVProgressHUDMaskTypeClear];
    ASNetworkEngine *networkingEngine = [ASNetworkEngine sharedInstance];
    [networkingEngine GET:prefix parameters:nil success:^(id responseObject) {
        NSDictionary* jsonRsp = (NSDictionary *)responseObject;
        if (isSuccessRsp(jsonRsp))
        {
            NSArray* data = [jsonRsp objectForKey:kASJsonData];
            for (NSInteger i = 0; i < [data count]; i++)
            {
                NSDictionary* dic = [data objectAtIndex:i];
                ASPoliticalInfo *info  = [[ASPoliticalInfo alloc] init];
                info.political = [[dic objectForKey:@"political"] integerValue];
                info. politicalName = [dic objectForKey:@"politicalName"];
                [weakSelf.politicalArray addObject:info];
            }
        }
        [SVProgressHUD dismiss];
    } failure:^(NSError *error) {
        //[SVProgressHUD showErrorWithStatus:error.description];
        [SVProgressHUD showErrorWithStatus:@"获取政治面貌失败"];
    }];
}

- (void)logout
{
    ASAppDelegate *appDelegate = [ASAppDelegate sharedAppDelegate];
    [appDelegate enterLoginView];
}

- (void)uploadPortraitImage:(UIImage *)headImage
{
    //上传用户头像接口 http://211.65.216.54/uploadAction.do?type=1&userCode=xiaohu type=1表示上传图片
    
    NSString* refer = @"uploadAction.do?type=1&userCode=";
    NSString* prefix = kASHttpUrl(refer);
    NSString* userCode = [ASAppDelegate sharedAppDelegate].userInfo.userCode;
    NSString* totalUrl = [prefix stringByAppendingString:userCode];
    
    [SVProgressHUD showWithStatus:@"上传头像..." maskType:SVProgressHUDMaskTypeClear];
    
    typeof(self) __weak weakSelf = self;
    ASNetworkEngine *netEngine = [ASNetworkEngine sharedInstance];
    [netEngine uploadImageWithUril:totalUrl image:headImage progressBlock:^(long long bytesRead, long long totalBytes) {
        
        float flt = 100 * bytesRead / totalBytes;
        NSString *progress = [NSString stringWithFormat:@"%f", flt];
        [SVProgressHUD showInfoWithStatus:progress];
    } completionBlock:^(id responseObject) {
        
        NSDictionary* jsonRsp = (NSDictionary *)responseObject;
        if (isSuccessRsp(jsonRsp))
        {
            weakSelf.headImage.image = headImage;
            [SVProgressHUD showSuccessWithStatus:@"头像上传成功"];
            
            // 上传成功 需要将headImage写入文件中保存
            [weakSelf writeImageToFile:headImage];
        }
    } failure:^(NSString *errorMsg) {
        [SVProgressHUD showErrorWithStatus:errorMsg.description];
    }];
}

- (void)writeImageToFile:(UIImage *)headImage
{
    NSString *headImageName = @"123.png";
    NSString *headImgPath = [self getHeadImageFilePath:headImageName];
    
    NSData *data = UIImagePNGRepresentation(headImage);
    if (data)
    {
        [data writeToFile:headImgPath atomically:YES];
    }
}

- (NSString*)getHeadImageFilePath:(NSString*)imageName
{
    NSString* path = [kFileUtil getAppDataPath];
    path = [path stringByAppendingPathComponent:@"HeadImg"];
    
    if (![kFileUtil isFileExist:path])
    {
        [kFileUtil createPath:path];
    }
    
    path = [path stringByAppendingPathComponent:imageName];
    
    return path;
}

- (BOOL)judgeFileExist:(NSString*)imageName
{
    NSString* path = [kFileUtil getAppDataPath];
    path = [path stringByAppendingPathComponent:@"HeadImg"];
    path = [path stringByAppendingPathComponent:imageName];
    
    return [kFileUtil isFileExist:path];
}

- (void)clickHeadImageBtn:(id)sender
{
    FTPhotoAlbumController* phoAlbum = [[FTPhotoAlbumController alloc] init];
    phoAlbum.albumDelegate = self;
    phoAlbum.albumType = AlbumType_SingleForPhoto;
    phoAlbum.photoCanEdit = YES;
    ASBaseNavigationController* baseNavi = [[ASBaseNavigationController alloc] initWithRootViewController:phoAlbum];
    [self presentViewController:baseNavi animated:YES completion:nil];
}

#pragma mark - FTAlbumPhotoViewControllerDelegate

- (void)albumDidFinishPickingWithInfo:(NSMutableArray *)info
                          IsOriginImg:(BOOL)isOriginImg
                        withAlbumType:(AlbumType)albumType
{
    if ([info count] > 0)
    {
        UIImage *image = [info objectAtIndex:0];
        [self uploadPortraitImage:image];
    }
}

#pragma mark - UITableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 50.0f;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (0 == [indexPath row])
    {
        // 此处需要判断 老师和学生的身份类型 进入不同的基本信息展示页面 //!角色类型（1 老师  2 学生 3管理员）
        NSString *sTypeId = [ASAppDelegate sharedAppDelegate].userInfo.sourceTypeId;
        
        if ([sTypeId isEqualToString:@"2"])
        {
            ASBasicInfoVC* basicInfoVC = [[ASBasicInfoVC alloc] initWithPolArray:_politicalArray];
            basicInfoVC.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:basicInfoVC animated:YES];
        }
        else
        {
            ASTeacherBasicInfoViewController *teaInfoVC = [[ASTeacherBasicInfoViewController alloc] init];
            teaInfoVC.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:teaInfoVC animated:YES];
        }
    }
//    else if (1 == [indexPath row])
//    {
//        ASMyCollectionVC* collecVC = [[ASMyCollectionVC alloc] init];
//        collecVC.hidesBottomBarWhenPushed = YES;
//        [self.navigationController pushViewController:collecVC animated:YES];
//    }
//    else if (2 == [indexPath row])
//    {
//        ASMyMessageVC* msgVC = [[ASMyMessageVC alloc] init];
//        msgVC.hidesBottomBarWhenPushed = YES;
//        [self.navigationController pushViewController:msgVC animated:YES];
//    }
    else if (1 == [indexPath row])
    {
        ASSettingViewController* setVC = [[ASSettingViewController alloc] init];
        setVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:setVC animated:YES];
    }
    else if (2 == [indexPath row])
    {
        ASScanQRCodeViewController* scanViewCtrl = [[ASScanQRCodeViewController alloc] init];
        scanViewCtrl.hidesBottomBarWhenPushed = YES;
        scanViewCtrl.delegate = self;
        [self.navigationController pushViewController:scanViewCtrl animated:YES];
    }
    else
    {
        return;
    }
}

#pragma mark - UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [_infoTypeArr count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([ASPersonCell class])];
    
    [(ASPersonCell*)cell updateCellStatus:[_leftBgImage objectAtIndex:[indexPath row]]
                                 cellName:[_infoTypeArr objectAtIndex:[indexPath row]]
                                 rowIndex:[indexPath row]];
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    return cell;
}

#pragma mark - ASScanQRCodeViewControllerDelegate
- (void)scanOk
{
    //[self.view rcsmakeToast:@"扫码成功" duration:0.5f position:@"center"];
}

@end



